<template>
  <div>
    <van-nav-bar title="评论" fixed left-arrow @click-left="$router.back()" />
    <div class="main">
      <van-pull-refresh v-model="isLoading" @refresh="onRefresh">
        <van-list
          v-model="loading"
          :finished="finished"
          finished-text="没有更多了"
          @load="onLoad"
        >
          <van-cell v-for="(obj, index) in list" :key="index">
            <template>
              <div class="wrap">
                <div class="img_wrap">
                  <img :src="obj.user.avatarUrl" alt="" />
                </div>
                <div class="content_wrap">
                  <div class="header_wrap">
                    <div class="info_wrap">
                      <p>{{ obj.user.nickname }}</p>
                      <p>{{ obj.time }}</p>
                    </div>
                    <div>{{ obj.likedCount }}点赞</div>
                  </div>
                  <div class="footer_wrap">
                    {{ obj.content }}
                  </div>
                </div>
              </div>
            </template>
          </van-cell>
        </van-list>
      </van-pull-refresh>
    </div>
  </div>
</template>

<script>
import { getCommentListAPI } from "@/api";

export default {
  data() {
    return {
      list: [], // 评论列表
      isLoading: false, // 加载的状态
      loading: false, // 加载状态（底部加载中）
      finished: false, // 如果为true，list下面就会显示没有数据
      page: 1, // 当前要请求第几页的数据
    };
  },
  methods: {
    async onRefresh() {
        this.list = []
        this.page = 1
        this.getList()
    },
    async getList() {
      const res = await getCommentListAPI({
        id: this.$route.query.id,
        limit: 20,
        // offset 分页
        offset: (this.page -1 ) * 20 // 这里必须和limit一致
      });
      res.data.comments.forEach(obj => this.list.push(obj)) // 第二页数据夹在第一页
      // this.list = res.data.comments;
      this.isLoading = false
      // 隐藏2: 每次请求完数据都要把loading关闭，负责不会再次触发onLoad()
      // 可能容易递归，必须要让数据相加
      this.loading = false  
    },
    async onLoad() {
      // 加载后loading 改为false
      // 隐藏问题: 网页刚打开list组件就相当于触底了，马上执行了一次onLoad事件
      this.getList()
      this.page++
    }
  },
  async created() {
    this.getList()
  },
};
</script>

<style lang="less" scoped>
.main {
  padding-top: 46px;
}
.wrap {
  display: flex;
}
.img_wrap {
  width: 0.8rem;
  height: 0.8rem;
  margin-right: 0.266667rem;
}
.img_wrap img {
  width: 100%;
  height: 100%;
  border-radius: 50%;
}
.content_wrap {
  flex: 1;
}
.header_wrap {
  display: flex;
}

.info_wrap {
  flex: 1;
}
.info_wrap p:first-child {
  font-size: 0.373333rem;
  color: #666;
}
.info_wrap p:last-of-type {
  font-size: 0.24rem;
  color: #999;
}
.header_wrap div:last-of-type {
  color: #999;
  font-size: 0.293333rem;
}

.footer_wrap {
  font-size: 0.4rem;
  color: #333;
}
</style>
